package com.fy.controller;

import com.fy.dao.ProductMapper;
import com.fy.dao.PtypeMapper;
import com.fy.dao.UserMapper;
import com.fy.dto.Document;
import com.fy.dto.ProductVo;
import com.fy.entity.Product;
import com.fy.entity.Ptype;
import com.fy.entity.User;
import com.fy.service.RoundService;
import com.fy.utils.CookieUtils;
import com.fy.utils.IdWorker;
import com.fy.utils.JwtUtils;
import com.fy.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RequestMapping("/product")
@RestController
public class ProductController {

    @Autowired
    @Qualifier("idWorker1")
    private IdWorker idWorker1;

    @Autowired
    @Qualifier("idWorker2")
    private IdWorker idWorker2;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RoundService roundService;

    @Autowired
    private PtypeMapper ptypeMapper;
    @Autowired
    private UserMapper userMapper;

    private User getUser(HttpServletRequest request){
        String token = request.getHeader("token");
        String account = JwtUtils.getAccount(token);
        User user = new User();
        user.setName(account);
        User singleUser = userMapper.selectOne(user);
        return singleUser;
    }

    @RequestMapping("/createProduct")
    public String createProduct(String name, Long typeId, String detail,MultipartFile[] imageUrl, HttpServletRequest request) throws IOException {
        if(Objects.equals(name,"")){
            return "商品名称不能为空!";
        }
        if(typeId == null){
            return "商品类型必须选择!";
        }
        if(Objects.equals(detail,"")){
            return "商品介绍不能为空!";
        }
        if(imageUrl==null){
            return "图片不能为空!";
        }
        //--判断前端传过来的图片是否图片名相同
        for (int i = 0; i < imageUrl.length - 1; i++) {
            for (int j = i + 1; j < imageUrl.length; j++) {
                if(Objects.equals(imageUrl[i].getOriginalFilename(), imageUrl[j].getOriginalFilename())){
                    return "上传的图片文件名与已上传的图片文件名相同，请重新选择图片!";
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < imageUrl.length; i++) {
            String originalFilename = imageUrl[i].getOriginalFilename();
            String newName = UUID.randomUUID().toString().replace("-", "").toUpperCase() + "-" + originalFilename;
            //--数据库的imgs路径
            String imgsrc = "http://192.168.201.136:10002/imgs/" + newName;
            //--将图片存入指定磁盘
            String readPath = "//DESKTOP-PE94E8O/imgs/" + newName;
            imageUrl[i].transferTo(new File(readPath));
            stringBuilder.append(imgsrc).append(";");
        }
        //--获取当前用户
        User user1 = getUser(request);
//        User user = UserUtils.getCurrUserFromHeader("token", User.class, request);
        Product product = new Product();
        product.setId(idWorker1.nextId());
        product.setName(name);
        product.setTypeid(typeId);
        product.setDetail(detail);
        product.setSalerid(user1.getId());
        product.setImgs(stringBuilder.toString());
        product.setCreatetime(new Date());
        product.setState(0);
        productMapper.insert(product);
        return "商品创建成功!!!";
    }

    @RequestMapping("/selectProductByState")
    public List<ProductVo> selectProductByState(HttpServletRequest request){
        //--获取当前用户
        User user = getUser(request);

        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        //-----------------------------------------------------------
        criteria.andEqualTo("salerid",user.getId());
        List<Product> products = productMapper.selectByExample(example);
        List<ProductVo> productVos = new ArrayList<>();
        for (Product product : products) {
            ProductVo productVo = new ProductVo();
            productVo.setProduct(product);
            if(product.getState() == 0){
                productVo.setStateName("未竞拍");
            }
            if(product.getState() == 1){
                productVo.setStateName("竞拍中");
            }
//            if(product.getState() == 2){
//                productVo.setStateName("已完成");
//            }
            Ptype ptype = ptypeMapper.selectByPrimaryKey(product.getTypeid());
            productVo.setTypeName(ptype.getTypename());
            productVos.add(productVo);
        }
        return productVos;
    }

    @RequestMapping("/modify")
    public List<Document> modify(@RequestBody Product product){
        //--处理数据库中的照片
        String imgs = product.getImgs();
        String[] urls = imgs.split(";");
        List<Document> documents = new ArrayList<>();
        for (int i = 0; i < urls.length; i++) {
            Document document = new Document();
            String[] split = urls[i].split("-");
            document.setName(split[1]);
            document.setUrl(urls[i]);
            documents.add(document);
        }
        return documents;
    }

    @RequestMapping("/updateInfo")
    public String updateInfo(Long productId,String name, Long typeId, String detail,Date createtime,MultipartFile[] imageUrl,String document,HttpServletRequest request) throws IOException {
        if(Objects.equals(name,"")){
            return "商品名称不能为空!";
        }
        if(typeId == null){
            return "商品类型必须选择!";
        }
        if(Objects.equals(detail,"")){
            return "商品介绍不能为空!";
        }
        if(Objects.equals(document,null)){
            return "图片不能为空！";
        }
        //--判断前端传过来的图片是否图片名相同
        String[] split = document.split(",");
        for (int i = 0; i < split.length - 1; i++) {
            for (int j = i + 1; j < split.length; j++) {
                if(Objects.equals(split[i], split[j])){
                    return "上传的图片文件名与已上传的图片文件名相同，请重新选择图片!";
                }
            }
        }

        //--校验完毕，正式开始
        List<String> newFilePath = new ArrayList<>();
        for (MultipartFile file : imageUrl) {
            String newName = UUID.randomUUID().toString().replace("-", "").toUpperCase() + "-" + file.getOriginalFilename();
            //--数据库的imgs路径
            String imgsrc = "http://192.168.201.136:10002/imgs/" + newName;
            //--将图片存入指定磁盘
            String readPath = "//DESKTOP-PE94E8O/imgs/" + newName;
            file.transferTo(new File(readPath));
            newFilePath.add(imgsrc);
        }

        Product product = productMapper.selectByPrimaryKey(productId);
        String imgs = product.getImgs();
        String[] img = imgs.split(";");
        //--组装新的imgSrcUrl;
        StringBuilder stringBuilder = new StringBuilder();
        //--前端顺序的文件名遍历
        for (String filename : split) {
            if(img.length != 0){
                //--数据库product表imgs字段的url遍历
                for (String s : img) {
                    if(s.contains(filename)){
                        stringBuilder.append(s).append(";");
                        break;
                    }
                }
            }
            if(newFilePath.size() != 0){
                //--前端新增加文件的文件名遍历
                for (String singleFilePath : newFilePath) {
                    if(singleFilePath.contains(filename)){
                        stringBuilder.append(singleFilePath).append(";");
                        break;
                    }
                }
            }
        }
        //--获取当前用户
//        User user = UserUtils.getCurrUserFromHeader("token", User.class, request);
        User user = getUser(request);
        Product newProduct = new Product();
        newProduct.setId(productId);
        newProduct.setName(name);
        newProduct.setTypeid(typeId);
        newProduct.setDetail(detail);
        newProduct.setSalerid(user.getId());
        newProduct.setImgs(stringBuilder.toString());
        newProduct.setCreatetime(createtime);
        newProduct.setUpdatetime(new Date());
        newProduct.setState(0);
        productMapper.updateByPrimaryKey(newProduct);
        return "商品修改成功!!!";
    }

    @RequestMapping("/selectByState")
    public List<Product> selectByState(HttpServletRequest request){
        //--获取当前用户
//        User user = UserUtils.getCurrUserFromHeader("token", User.class, request);
        User user = getUser(request);

        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("salerid",user.getId()).andEqualTo("state",0);
        List<Product> products = productMapper.selectByExample(example);
        return products;
    }

    @RequestMapping("/modifyStateById")
    public int modifyStateById(Long productId,Integer state){
        return roundService.modifyStateById(productId,state);
    }

}
